#include "../common/common_modbus.h"
#include "../common/common_modbus_485_port.h"
#include "../../bsp/cli_cmd.h"
#include "led_banner.h"
#include "../common/device_manager.h"


/**
 *  @brief 洗车机控制led指示牌
 */
static unsigned short get_iocode_by_display_item(u8 item)
{
/**
 *  显示节目单号
 */
    u8 iocode_map_to_display[16] = {
    /*iocode_map_to_display[0] =  */1,   // 智能洗车
    /*iocode_map_to_display[1] =  */2,   // 请前进
    /*iocode_map_to_display[2] =  */3,   // 请后退
    /*iocode_map_to_display[3] =  */4,   // 请停车
    /*iocode_map_to_display[4] =  */5,   // 左侧压线
    /*iocode_map_to_display[5] =  */6,   // 右侧压线
    /*iocode_map_to_display[6] =  */0,
    /*iocode_map_to_display[7] =  */8,   // 请扫码
    /*iocode_map_to_display[8] =  */9,   // 请停车
    /*iocode_map_to_display[9] =  */23,  // 车辆超长
    /*iocode_map_to_display[10] = */77,  // 服务异常
    /*iocode_map_to_display[11] = */86,  // 立体风干
    /*iocode_map_to_display[12] = */87,  // 环绕清洗
    /*iocode_map_to_display[13] = */88,  // 开始洗车
    /*iocode_map_to_display[14] = */98,  // 请勿移动
    /*iocode_map_to_display[15] = */99   // 已完成
    };
    for (int i = 1; i < 16; i ++) {
        if (item == iocode_map_to_display[i]) return i;
    }
    return 0;
}

#if 0
static void set_iocode_to_iopin(u8 code)
{
    u8 iopin_bits[XP_WASHCAR_DISPLAY_IO_BITS] = {
        XP_WASHCAR_DISPLAY_IO_BIT0,
        XP_WASHCAR_DISPLAY_IO_BIT1,
        XP_WASHCAR_DISPLAY_IO_BIT2,
        XP_WASHCAR_DISPLAY_IO_BIT3,
    };
    for (int i = 0; i < sizeof(iopin_bits); i ++) 
        xp_io_write_pin(1, iopin_bits[i], (code & (0x01 << i))?0:1);
}
#endif

/*  */
int xp_led_banner_item_set(struct xp_modbus_device *banner, int item_no)
{
    if (banner == NULL) return -1;
    unsigned short item = get_iocode_by_display_item(item_no);
    unsigned short addr = 0x0FA0;
    unsigned short data = item;
    if (banner == NULL || banner->inited != 1)
        return -1;
    int ret = banner->bus->swrite(banner, addr, data);

    return (ret != 0) ? -1 : 0;
}

int xp_led_banner_debug(char *type, char *fun, char *param)
{
    if (strcmp(type, "led_banner") != 0)
        return 0;

    struct xp_modbus_device *banner = get_modbus_device_by_name((unsigned char *)"led_banner");
    if (banner == NULL)
        return 0;
    if (strcmp(fun, "set") == 0)
    {
        println("led banner set no of item : %s", param);
        xp_led_banner_item_set(banner, atoi(param));
    }

    return 1;
}
